import Vuex from 'vuex'

function loadModules (fileList) {
  return fileList.keys().reduce((modules, modulePath) => {
    const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
    const value = fileList(modulePath)
    modules[moduleName] = value.default
    return modules
  }, {})
}

const modules = loadModules(require.context('./modules', true, /\.js$/))

export function Store (Vue) {
  Vue.use(Vuex)
  const store = Object.assign(new Vuex.Store({
    modules: modules,
    getters: {
      keepAlive: state => state.keepAlive.pathList
    }
  }), {
    __loading_count__: 0,
    setLoginUser (info) {
      this.commit('user/SET_INFO', info)
    },
    getLoginUser () {
      return this.state.user.info
    },
    setMenu (menuList, menuMap) {
      this.commit('user/SET_MENU', { menuList, menuMap })
    },
    getMenu () {
      return this.state.user.menu
    },
    getMenuMap () {
      return this.state.user.menuMap
    },
    setThemes (themes) {
      this.commit('user/SET_THEMES', themes)
    },
    getThemes () {
      return this.state.user?.themes || {}
    },
    getTheme (key, defVal) {
      return this.getThemes()[key] || defVal
    },
    getAppConfig (key, def) {
      return this.state.app.configs[key] || def
    },
    setAppConfig (configs) {
      this.commit('app/SET_CONFIGS', configs)
    },
    removeAppConfig (key) {
      this.commit('app/REMOVE', key)
    },
    showLoading () {
      this.__loading_count__++
      this.commit('app/SHOW_LOADING')
    },
    hideLoading () {
      this.__loading_count__ > 0 && this.__loading_count__--
      !this.__loading_count__ && this.commit('app/HIDE_LOADING')
    },
    updateKeepAlive (pages) {
      this.commit('keepAlive/UPDATE', pages || [])
    },
    getKeepAlive () {
      return this.state.keepAlive.pathList
    }
  })
  store.setAppConfig(JSON.parse(localStorage.getItem('appConfig') || '{}'))
  return store
}
